// uni-app H5适配层
// 为了让uni-app语法在普通Vue项目中也能运行

interface UniAPI {
  showToast: (options: { title: string; icon?: 'success' | 'error' | 'loading' | 'none'; duration?: number }) => void
  showModal: (options: { title: string; content: string; confirmText?: string; cancelText?: string; success?: (res: { confirm: boolean; cancel: boolean }) => void }) => void
  getStorageSync: (key: string) => any
  setStorageSync: (key: string, value: any) => void
  removeStorageSync: (key: string) => void
  clearStorageSync: () => void
  getSystemInfoSync: () => any
  getStorageInfoSync: () => { keys: string[]; currentSize: number; limitSize: number }
  getNetworkType: (options: { success: (res: { networkType: string }) => void }) => void
  onNetworkStatusChange: (callback: (res: { isConnected: boolean; networkType: string }) => void) => void
  downloadFile: (options: { url: string; success?: (res: { tempFilePath: string }) => void }) => void
  openDocument: (options: { filePath: string }) => void
  vibrateShort?: (options?: any) => void
  vibrateLong?: (options?: any) => void
  setClipboardData?: (options: { data: string; success?: () => void; fail?: (err: any) => void }) => void
}

// 模拟uni API
const createUniAPI = (): UniAPI => {
  return {
    showToast: (options) => {
      const { title, icon = 'none', duration = 1500 } = options

      // 创建toast元素
      const toast = document.createElement('div')
      toast.className = 'uni-toast'
      toast.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 12px 16px;
        border-radius: 8px;
        font-size: 14px;
        z-index: 10000;
        text-align: center;
        max-width: 200px;
        word-wrap: break-word;
      `

      // 添加图标
      if (icon !== 'none') {
        const iconMap = {
          success: '✅',
          error: '❌',
          loading: '⏳'
        }
        toast.innerHTML = `<div style="margin-bottom: 4px;">${iconMap[icon] || ''}</div>${title}`
      } else {
        toast.textContent = title
      }

      document.body.appendChild(toast)

      // 自动移除
      setTimeout(() => {
        if (toast.parentNode) {
          toast.parentNode.removeChild(toast)
        }
      }, duration)
    },

    showModal: (options) => {
      const { title, content, confirmText = '确定', cancelText = '取消', success } = options

      if (window.confirm(`${title}\n${content}`)) {
        success?.({ confirm: true, cancel: false })
      } else {
        success?.({ confirm: false, cancel: true })
      }
    },

    getStorageSync: (key) => {
      try {
        const value = localStorage.getItem(key)
        return value ? JSON.parse(value) : null
      } catch {
        return localStorage.getItem(key)
      }
    },

    setStorageSync: (key, value) => {
      try {
        localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value))
      } catch (error) {
        console.error('setStorageSync failed:', error)
      }
    },

    removeStorageSync: (key) => {
      localStorage.removeItem(key)
    },

    clearStorageSync: () => {
      localStorage.clear()
    },

    getSystemInfoSync: () => {
      return {
        platform: 'h5',
        system: navigator.platform,
        version: navigator.appVersion,
        screenWidth: window.screen.width,
        screenHeight: window.screen.height,
        windowWidth: window.innerWidth,
        windowHeight: window.innerHeight,
        pixelRatio: window.devicePixelRatio || 1,
        language: navigator.language,
        model: 'H5',
        brand: 'H5'
      }
    },

    getStorageInfoSync: () => {
      const keys = Object.keys(localStorage)
      let currentSize = 0

      try {
        const testData = JSON.stringify(localStorage)
        currentSize = new Blob([testData]).size
      } catch (error) {
        console.error('计算存储大小失败:', error)
      }

      return {
        keys,
        currentSize: Math.round(currentSize / 1024), // 转换为KB
        limitSize: 5 * 1024 // 假设限制5MB
      }
    },

    getNetworkType: (options) => {
      // H5环境下的网络检测
      const connection = (navigator as any).connection || (navigator as any).mozConnection || (navigator as any).webkitConnection
      const networkType = connection ? connection.effectiveType || 'unknown' : 'unknown'

      options.success({ networkType })
    },

    onNetworkStatusChange: (callback) => {
      // 监听在线/离线状态
      const handleOnline = () => callback({ isConnected: true, networkType: 'wifi' })
      const handleOffline = () => callback({ isConnected: false, networkType: 'none' })

      window.addEventListener('online', handleOnline)
      window.addEventListener('offline', handleOffline)

      // 返回取消监听的函数
      return () => {
        window.removeEventListener('online', handleOnline)
        window.removeEventListener('offline', handleOffline)
      }
    },

    downloadFile: (options) => {
      const { url, success } = options

      // H5环境下的下载实现
      const link = document.createElement('a')
      link.href = url
      link.download = url.split('/').pop() || 'download'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      success?.({ tempFilePath: url })
    },

    openDocument: (options) => {
      const { filePath } = options
      // H5环境下打开文档
      window.open(filePath, '_blank')
    },

    vibrateShort: (options = {}) => {
      if (navigator.vibrate) {
        navigator.vibrate(50)
      }
    },

    vibrateLong: (options = {}) => {
      if (navigator.vibrate) {
        navigator.vibrate(200)
      }
    },

    setClipboardData: (options) => {
      const { data, success, fail } = options

      if (navigator.clipboard) {
        navigator.clipboard.writeText(data)
          .then(() => success?.())
          .catch((err) => fail?.(err))
      } else {
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = data
        document.body.appendChild(textArea)
        textArea.select()
        try {
          document.execCommand('copy')
          document.body.removeChild(textArea)
          success?.()
        } catch (err) {
          document.body.removeChild(textArea)
          fail?.(err)
        }
      }
    }
  }
}

// 创建全局uni对象
declare global {
  var uni: UniAPI
}

if (typeof window !== 'undefined' && !window.uni) {
  window.uni = createUniAPI()
}

export default createUniAPI()